package com.kb.medical.controller;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.kb.medical.controller.ex.FileUploadIOException;
import com.kb.medical.entity.*;
import com.kb.medical.service.FileService;
import com.kb.medical.service.IUserService;
import com.kb.medical.service.PdfImageService;
import com.kb.medical.service.PdfTxtService;
import com.kb.medical.service.es.EsService;
import com.kb.medical.util.JsonResult;
import com.kb.medical.util.Text_Pdf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController//@Controller+@ResponseBody
@RequestMapping("files")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;
    @Autowired
    private PdfImageService pdfImageService;
    @Autowired
    private PdfTxtService pdfTxtService;
    @Autowired
    private IUserService userService;
    @Autowired
    private EsService esService;

    /**
     * @param request
     * @return 多文件上传
     */
    @PostMapping("/uploads")
    @Transactional
    public JsonResult<Void> handleFileUpload(HttpServletRequest request) {
        // 校验当前客户端是否已经登录，如果未登录则抛出 `NotLoginException` 异常
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (SaTokenException e) {
            SaResult result = new SaResult().setCode(401);
        }
        JsonResult result = new JsonResult<>(OK);
        //查询当前的用户id
        User data = userService.getByUserid(StpUtil.getLoginIdAsInt());
        System.out.println(data.getUserid());
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

        MultipartFile file = null;
        String[] folders = new String[files.size()];
        /** 获取当前系统时间*/
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);

            if (!file.isEmpty()) {
                try {
                    UserFile fileContext = new UserFile();
                    //查询当前的用户id
                    int userid = StpUtil.getLoginIdAsInt();
//                    int userid = 41;
                    //获取原始文字
                    String filename = file.getOriginalFilename();
//                    System.out.println("上传文件名"+filename);

                    int dotIndex = filename.lastIndexOf(".");
                    if (fileService.getByFileName(filename.substring(0, dotIndex)) == null) {
                        //保存文件路径
                        String filePath = fileService.createFolder(userid);
                        String destPath = filePath + "/" + filename;

//                    System.out.println("222"+destPath);

                        //文件对象
                        File dest = new File(destPath);

                        //保存到服务器
                        file.transferTo(dest);


                        //文件信息存入fileContext对象中
                        fileContext.setFileName(fileService.pdfRename(filename));
                        fileContext.setUserid(userid);
                        //正式的换电脑本地路径
                        fileContext.setPdfPath(filePath + "/" + filename);
                        fileContext.setUploadUserName(userService.getByUserid(userid).getUsername());

                        //保存的是局域网文件路径
//                    String localPath = fileService.localPath(destPath);

//                    fileContext.setPdfPath(localPath);

                        //文件信息存储到数据库
                        fileService.fileInsert(fileContext);

                        //获取当前文件的documentId
                        UserFile idContext = fileService.getByFileName(fileService.pdfRename(filename));

                        int DocumentId = idContext.getId();
//                    System.out.println(DocumentId);

                        //pdf文件提取信息
                        String pdPath = filePath + "/" + filename;
                        //pdf的文件路径+名字
                        Text_Pdf.extractTextFromPdf(pdPath);


                        //pdf文件去除后缀获得存放图片的文件夹
                        String ImgPath = filePath + "/pic/" + filename.substring(0, filename.lastIndexOf("."));

                        //pdf去除错误图片
                        Text_Pdf.deleteImgError(ImgPath);

                        //图片ocr提取信息并写入到数据库
                        PdfImage pdfImage = new PdfImage();
                        pdfImage.setDocumentId(DocumentId);
                        pdfImage.setUserid(userid);
                        pdfImage.setUploadTime(new Date());
                        pdfImage.setUploadUserName(userService.getByUserid(userid).getUsername());
                        pdfImage.setPath(ImgPath);
//                    System.out.println(pdfImage);
                        pdfImageService.TextFromImg(idContext, pdfImage);
//                    System.out.println(11);

                        //读取和写入信息到数据库
                        String TextPath = filePath + "/text/" + filename.substring(0, filename.lastIndexOf("."));
//                    System.out.println("textpath"+TextPath);
                        String pdfInsert = pdfTxtService.ReadFile(idContext, TextPath);


                        //pdf获取总页数和更新到数据库
                        fileService.updatePage(DocumentId, TextPath);

                        // 删除提取信息后的垃圾文件
                        String picPath = filePath + "/pic";
                        String textPath = filePath + "/text";
                        fileService.deleteFolder(picPath);
                        fileService.deleteFolder(textPath);
                        result.setMessage("上传成功！");
                    } else {
                        result.setMessage("上传成功,重复的文件请先删除后再上传!");
                        folders[i] = "已存在该文件名:" + file.getOriginalFilename().substring(0, dotIndex);
                    }


                } catch (IOException e) {

                    throw new FileUploadIOException("文件上传错误");
                }
            } else {

                throw new FileUploadIOException("文件上传错误");
            }

        }


/** 获取当前的系统时间，与初始时间相减就是程序运行的毫秒数，除以1000就是秒数*/
        long endTime = System.currentTimeMillis();
        long usedTime = (endTime - startTime) / 1000;
        System.out.println(usedTime);

        result.setState(200);

        result.setData(folders);

        return result;
    }


    /**
     * 查看当前用户上传的文献
     *
     * @param n 页数
     * @return 返回多个文件对象
     */
    @RequestMapping("/getFileList")
    public JsonResult<List<UserFile>> getFileList(int n) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User user = userService.getByUserid(StpUtil.getLoginIdAsInt());
        List<UserFile> data = fileService.findByUserid(user.getUserid(), n);
        return new JsonResult<List<UserFile>>(OK, data);
    }

//http://172.16.245.231:8080/uploadFile/41/影响人工关节置换术后下肢深静脉血栓形成的临床风险因素分析_关振鹏.pdf


    @RequestMapping("/showPdf")
    public void pdfStreamHandler(int documentId, HttpServletResponse response) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User user = userService.getByUserid(StpUtil.getLoginIdAsInt());
        String fff = fileService.pdfDownload(documentId);
        //PDF文件地址
        File file = new File(fff);
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input = null;
            try {
                input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/deleteFile")

    public JsonResult deleteFile(int documentId) {

        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User user = userService.getByUserid(StpUtil.getLoginIdAsInt());
        JsonResult result = new JsonResult();
        if (fileService.deleteDataByDocumentId(user.getUserid(), documentId) == 1) {
            result.setState(200);
            result.setMessage("文献删除成功");
        } else {
            result.setState(500);
            result.setMessage("该文献不存在");
        }
        return result;
    }

    @PostMapping("/click")
    public void updateClickByDocId(int id) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User user = userService.getByUserid(StpUtil.getLoginIdAsInt());
        UserFile userFile = fileService.getById(id);
        int click = userFile.getClick() + 1;
        if (userFile.getScore() <= 100) {
            fileService.updateClickByDocId(click, id);
        }


    }

    @PostMapping("/like")
    public JsonResult<Void> updateLikeAddByDocId(int id) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User user = userService.getByUserid(StpUtil.getLoginIdAsInt());
        UserFile userFile = fileService.getById(id);

        int like = userFile.getLike() + 1;
        if (userFile.getScore() <= 100) {
            fileService.updateLikeByDocId(like, id);
        }
        JsonResult result = new JsonResult<>(OK);
        result.setState(200);
        result.setMessage("点赞成功！");
        return result;
    }

    @PostMapping("/dislike")
    public JsonResult<Void> updateDislikeByDocId(int id) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User user = userService.getByUserid(StpUtil.getLoginIdAsInt());
        UserFile userFile = fileService.getById(id);

        int like = userFile.getLike() - 1;
        if (userFile.getScore() <= 100) {
            if (userFile.getLike() != 0) {
                fileService.updateLikeByDocId(like, id);

            }
        }
        JsonResult result = new JsonResult<>(OK);
        result.setState(200);
        return result;
    }


    /**
     * 下载pdf
     *
     * @param id
     * @param request
     * @param response
     */
    @GetMapping("/downloadFile")
    public JsonResult downloadCheck(int id, HttpServletRequest request, HttpServletResponse response) {
        JsonResult result = new JsonResult();

        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        UserFile fileById = fileService.getById(id);
        if (fileById == null) {
            result.setMessage("文件不存在");
            result.setData(404);
            return result;
        }
        try {
            File file = new File(fileById.getPdfPath());
            BufferedInputStream bis = null;
            OutputStream os = null;
            FileInputStream fileInputStream = null;

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileById.getFileName().getBytes("gb2312"), "ISO8859-1") + ".pdf");

            try {
                fileInputStream = new FileInputStream(file);
                byte[] buff = new byte[1024];
                bis = new BufferedInputStream(fileInputStream);
                os = response.getOutputStream();

                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    i = bis.read(buff);
                    os.flush();
                }
                os.flush();
                os.close();
//                return SimpleResult.ok("导出成功",os);
            } catch (IOException e) {
                e.printStackTrace();
//                return SimpleResult.fail("导出失败",null);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
//                        return SimpleResult.fail("导出失败",null);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setMessage("下载成功");
        result.setState(200);
        return result;
    }

//    public static void setFileDownloadHeader(HttpServletRequest request,
//                                             HttpServletResponse response, String fileName) {
//        try {
//            String encodedFileName = null;
//            String agent = request.getHeader("USER-AGENT");
//            if (null != agent && -1 != agent.indexOf("MSIE")) {
//                encodedFileName = URLEncoder.encode(fileName, "UTF-8");
//            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
//                encodedFileName = new String(fileName.getBytes("UTF-8"),
//                        "iso-8859-1");
//            } else {
//                encodedFileName = URLEncoder.encode(fileName, "UTF-8");
//            }
//
//            response.setHeader("Content-Disposition", "attachment; filename=\""
//                    + encodedFileName + "\"");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


    /**
     * 预览pdf
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @GetMapping("/preview")
    public JsonResult previewCheck(int id, HttpServletResponse response) throws
            IOException {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }

        UserFile fileById = fileService.getById(id);
        JsonResult result = new JsonResult();
        if (fileById == null) {
            result.setData(404);
            result.setMessage("文件不存在");
            return result;
        }
//        FileInputStream is = new FileInputStream(new File(fileById.getPdfPath()));
        File file = new File(fileById.getPdfPath());
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input = null;
            try {
                input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);

                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        result.setState(200);
        return result;
    }

    @GetMapping("/previewuser")
    public JsonResult previewUser(HttpServletResponse response) throws
            IOException {


        JsonResult result = new JsonResult();

//        FileInputStream is = new FileInputStream(new File(fileById.getPdfPath()));
        File file = new File("D:\\javacode\\medical\\src\\main\\resources\\userPdf\\用户操作手册.pdf");
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input = null;
            try {
                input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);

                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        result.setState(200);
        return result;
    }


    @GetMapping("/search")
    public JsonResult<List<Es>> search(String searchKey) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        User data = userService.getByUserid(StpUtil.getLoginIdAsInt()); //查询当前的用户id
        List<Es> list = esService.search(searchKey, data.getUserid());
        JsonResult result = new JsonResult<>(OK);
        result.setState(200);
        result.setMessage("检索成功");
        result.setData(list);
        return result;

    }

    //    用户收藏
    @PostMapping("/collect")
    public JsonResult collect(int id, int documentid, String type, float relativeScore, float score,
                              int like, int click, String filename, String pdftext, int page, String uploadUserName, String searchKey) {

        EsStar esStar = new EsStar();
        esStar.setScore(score);
        esStar.setRelativeScore(relativeScore);
        esStar.setId(id);
        esStar.setPage(page);
        esStar.setType(type);
        esStar.setLike(like);
        esStar.setFilename(filename);
        esStar.setDocumentid(documentid);
        esStar.setClick(click);
        esStar.setPdftext(pdftext);
        esStar.setUploadUserName(uploadUserName);
        esStar.setSearchKey(searchKey);
        // 定义所需的日期时间格式
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String formattedDate = dateFormat.format(date);
        esStar.setStarTime(formattedDate);
        JsonResult result = new JsonResult<>(OK);
        result.setState(200);
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        User data = userService.getByUserid(StpUtil.getLoginIdAsInt()); //查询当前的用户id
        if (esService.starByUserId(data.getUserid(), esStar) == 1) {
            result.setMessage("收藏成功");
        } else {
            result.setMessage("已取消收藏");
        }
        return result;
    }

    /**
     * 查看当前用户的收藏夹
     *
     * @return
     */
    @GetMapping("/collectShow")
    public JsonResult<List<EsStar>> collectShow() {
        JsonResult result = new JsonResult<>(OK);
        result.setState(200);
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        //查询当前的用户id
        User data = userService.getByUserid(StpUtil.getLoginIdAsInt());

        result.setMessage("查询成功");
        List<EsStar> list = esService.selectStarByUserId(data.getUserid());
        result.setData(list);
        return result;
    }

    @GetMapping("searchBytype")
    public JsonResult<List<Es>> searchByType(String searchKey, String type) {
        try {
            StpUtil.getTokenInfo().getIsLogin();//检测是否登录
        } catch (Exception e) {
            throw new SaTokenException("用户没有登陆").setCode(401);
        }
        User data = userService.getByUserid(StpUtil.getLoginIdAsInt()); //查询当前的用户id
        List<Es> list = esService.searchByType(searchKey, data.getUserid(), type);
        JsonResult result = new JsonResult<>(OK);
        result.setState(200);
        result.setMessage("检索成功");
        result.setData(list);
        return result;
    }


}
